package com.atguigu.yygh.hosp.service.impl;

import com.atguigu.yygh.common.handler.YYGHException;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.repository.UserScheduleRepository;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.hosp.service.UserScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author:hx
 * @DateTime:2022/11/16 18:14
 * @Description:
 */
@Service
public class UserScheduleServiceImpl implements UserScheduleService {

    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private UserScheduleRepository userScheduleRepository;

    @Override
    public Map<String, Object> scheduleDatePage(Integer pageNum, Integer pageSize, String hoscode, String depcode) {
        //查询预约规则
        Hospital hospital = hospitalRepository.getByHoscode(hoscode);
        if (hospital == null){
            throw new YYGHException(20001,"该医院不存在!");
        }
        BookingRule bookingRule = hospital.getBookingRule();

        //获取排班日期分页数据
        Page<Date> page = this.currentDateList(pageNum,pageSize,bookingRule);
        List<Date> records = page.getRecords();

        //查询当前页日期所在的数据
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(records)),
                Aggregation.group("workDate").first("workDate").as("workDate")
                            .sum("availableNumber").as("availableNumber"),
                Aggregation.sort(Sort.by(Sort.Order.asc("workDate")))
        );
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> mappedResults = aggregate.getMappedResults();
        Map<Date, BookingScheduleRuleVo> collect = mappedResults.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));


        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        //判断每天的预约状态
        for (int i = 0; i < records.size(); i++) {
            Date date = records.get(i);

            BookingScheduleRuleVo bookingScheduleRuleVo = collect.get(date);

            if (bookingScheduleRuleVo == null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                bookingScheduleRuleVo.setWorkDate(date);
                bookingScheduleRuleVo.setAvailableNumber(-1);
                bookingScheduleRuleVo.setStatus(0);
            }

            bookingScheduleRuleVo.setStatus(0);

            if(pageNum==1 && i==0){
                DateTime dateTime = getDateTime(new Date(), bookingRule.getStopTime());
                if(dateTime.isBeforeNow()){
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }


            //获取每个日期对应的星期
            bookingScheduleRuleVo.setDayOfWeek(this.getDayOfWeek(new DateTime(date)));

            //设置末尾日期的状态
            if (pageNum == page.getPages() && i == records.size() - 1){
                bookingScheduleRuleVo.setStatus(1);
            }

            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("total",page.getTotal());
        map.put("bookingScheduleList",bookingScheduleRuleVoList);

        //获取其他的信息
        Map<String,Object> baseMap = new HashMap<>();
        baseMap.put("hosname",hospitalRepository.getByHoscode(hoscode).getHosname());
        baseMap.put("bigname",departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode,depcode).getBigname());
        baseMap.put("depname",departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode,depcode).getDepname());
        baseMap.put("workDateString",new DateTime().toString("yyyy年MM月"));
        baseMap.put("releaseTime",bookingRule.getReleaseTime());
        map.put("baseMap",baseMap);
        return map;
    }

    //日期分页数据
    private Page<Date> currentDateList(Integer pageNum, Integer pageSize, BookingRule bookingRule){
        //获取当天放号的时间
        DateTime dateTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());

        //判断今天是否在预约时间内
        Integer cycle = bookingRule.getCycle();
        if (dateTime.isBeforeNow()){
            cycle += 1;
        }

        //获取所有可预约的日期列表
        List<Date> dateTimeList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime plus = dateTime.plusDays(i);
            String dateTimeString = plus.toString("yyyy-MM-dd");
            dateTimeList.add(new DateTime(dateTimeString).toDate());
        }

        //只返回当前页数据
        Integer start = (pageNum - 1) * pageSize;
        Integer end = (pageNum - 1) * pageSize + pageSize;
        if (end > dateTimeList.size()){
            end = dateTimeList.size();
        }

        List<Date> currentDateList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            currentDateList.add(dateTimeList.get(i));
        }

        Page<Date> page = new Page<>(pageNum,pageSize,dateTimeList.size());
        page.setRecords(currentDateList);
        return page;
    }

    private DateTime getDateTime(Date date,String releaseTime){
        String dateTime = new DateTime(date).toString("yyyy-MM-dd") + " " + releaseTime;
        DateTime parseDateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTime);
        return parseDateTime;
    }

    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    @Override
    public List<Schedule> findScheduleList(String hoscode, String depcode, String workDate) {
        List<Schedule> scheduleDetail = scheduleService.getScheduleDetail(hoscode, depcode, workDate);
        return scheduleDetail;
    }

    @Override
    public Schedule getSchedule(String id) {
        Schedule schedule = mongoTemplate.findById(id, Schedule.class);
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        schedule.getParam().put("hosname",hospitalRepository.getByHoscode(schedule.getHoscode()).getHosname());
        schedule.getParam().put("depname",departmentRepository.getDepartmentByHoscodeAndDepcode(schedule.getHoscode(),schedule.getDepcode()).getDepname());
        return schedule;
    }

    @Override
    public ScheduleOrderVo getScheduleOrder(String hosScheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();

        //获取排班信息
        Schedule schedule = new Schedule();
        schedule.setId(hosScheduleId);
        Example<Schedule> example = Example.of(schedule);
        Schedule mongoSchedule = userScheduleRepository.findOne(example).get();

        //获取医院信息
        Hospital hospital = hospitalRepository.getByHoscode(mongoSchedule.getHoscode());
        BookingRule bookingRule = hospital.getBookingRule();

        //将查询到的排班信息设置到ScheduleOrderVo中
        BeanUtils.copyProperties(mongoSchedule,scheduleOrderVo);
        scheduleOrderVo.setReserveDate(mongoSchedule.getWorkDate());
        scheduleOrderVo.setDepname(departmentRepository.getDepartmentByHoscodeAndDepcode(scheduleOrderVo.getHoscode(),scheduleOrderVo.getDepcode()).getDepname());

        //设置退号时间
        Date quitTime = this.getDateTime(new DateTime(scheduleOrderVo.getReserveDate()).plusDays(bookingRule.getQuitDay()).toDate()
                ,bookingRule.getQuitTime()).toDate();
        scheduleOrderVo.setQuitTime(quitTime);

        //设置挂号开始时间
        Date startTime = this.getDateTime(new Date(),bookingRule.getReleaseTime()).toDate();
        scheduleOrderVo.setStartTime(startTime);

        //设置挂号结束时间
        Date endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(),bookingRule.getStopTime()).toDate();
        scheduleOrderVo.setEndTime(endTime);

        //设置当天停止挂号时间
        Date stopTime = this.getDateTime(mongoSchedule.getWorkDate(),bookingRule.getStopTime()).toDate();
        scheduleOrderVo.setStopTime(stopTime);

        //将查询到的医院信息设置到ScheduleOrderVo中
        BeanUtils.copyProperties(hospital,scheduleOrderVo);

        return scheduleOrderVo;
    }
}
